<template>
  <div class="rolse">
    <!-- 顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="roles-card">
      <!-- 为用户添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" class="roles-card-button" @click="addRolePop">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 用户角色 -->
      <el-table
        :data="roleslist"
        border
        stripe
      >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, i1) in scope.row.children"
              :key="item.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                closable
                @close="removeRightById(scope.row, item.id)"
                >
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限 -->
                <el-row  v-for="(item2, i2) in item.children" :key="item2.id" :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']">
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="360">
          <template slot-scope="scope">
            <!-- 编辑角色弹窗 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRoleById(scope.row.id)">编辑</el-button>
            <template>
              <!-- 删除角色弹窗 -->
              <el-button type="danger" size="mini" icon="el-icon-delete-solid" @click="delRoleInfo(scope.row.id)">删除</el-button>
            </template>
            <!-- 分配权限 -->
            <el-button type="warning" size="mini" icon="el-icon-s-tools" @click="showRoleRight(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form :model="addRole" :rules="addRoleRules" ref="addRoleRef">
        <el-form-item label-width="80px" label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label-width="80px" label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolsInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoledialogVisible"
      width="30%"
    >
      <el-form :model="editRole" :rules="addRoleRules" ref="editRoleRef">
        <el-form-item label-width="80px" label="角色名称" prop="roleName">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label-width="80px" label="角色描述" prop="roleDesc">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleaddRolsInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="rightDialogClose"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="treeList"
        show-checkbox
        :props="treeProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      dialogVisible: false,
      editRoledialogVisible: false,
      roleslist: [],
      treeList: [],
      editRole: {},
      rightDialogVisible: false,
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名长度在3～10个字符之间', trigger: 'blur' }
        ]
      },
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // &默认选中的节点ID
      defKeys: [],
      treeId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    getRolesList () {
      this.$http.getRolesList()
        .then(resp => {
          const { data } = resp
          // console.log(data)
          if (data.meta.status !== 200) {
            return this.$message.error('获取角色列表失败')
          }
          this.roleslist = data.data
        })
    },
    // *添加角色弹框
    addRolePop () {
      this.addRole = {}
      this.dialogVisible = true
    },
    // *添加角色
    addRolsInfo () {
      this.$refs.addRoleRef.validate(vaild => {
        // console.log(vaild)
        // console.log(this.$refs.addRoleRef)
        if (!vaild) return
        this.$http.addRolsInfo(this.addRole)
          .then(resp => {
            // console.log(resp)
            const { data } = resp
            if (data.meta.status === 201) {
              this.$message.success(data.meta.msg)
              this.dialogVisible = false
              this.getRolesList()
            }
          })
      })
    },
    // *用户角色编辑按钮
    editRoleById (id) {
      this.editRoledialogVisible = true
      // *根据ID查询角色
      this.$http.getRoleById(id)
        .then(resp => {
          // console.log(resp)
          this.editRole = resp.data.data
        })
    },
    // *确定提交编辑角色
    editRoleaddRolsInfo () {
      // console.log(this.editRole)
      this.$http.putEditRole(this.editRole.roleId, this.editRole)
        .then(resp => {
          // console.log(resp)
          const { data } = resp
          if (data.meta.status !== 200) {
            return this.$message.error('修改角色失败')
          }
          this.$message.success('修改角色成功')
          this.editRoledialogVisible = false
          this.getRolesList()
        })
    },
    // *删除用户角色
    delRoleInfo (id) {
      this.$confirm('此操作将删除该角色, 是否继续?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delRoleInfo(id)
          .then(resp => {
            this.getRolesList()
          })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // console.log(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // *根据ID删除三级权限
    async removeRightById (role, rightId) {
      const confirmResult = await
      this.$confirm('此操作将删除该权限, 是否继续?', '删除权限', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // console.log(roleId.id, rightId)
      this.$http.delRoleRight(role.id, rightId)
        .then(resp => {
          const { data } = resp
          if (data.meta.status !== 200) {
            return this.$message.error('删除权限失败')
          }
          this.$message.success('删除成功')
          // this.getRolesList()
          role.children = data.data
        })
    },
    // *展示分配权限对话框
    showRoleRight (role) {
      this.$http.getRightsListTree()
        .then(resp => {
          const { data } = resp
          if (data.meta.status !== 200) {
            return this.$message.error('获取用户权限失败')
          }
          this.treeId = role.id
          this.treeList = data.data
        })
      //* =>递归获取三级节点ID
      // console.log(role)
      this.getLeafKeys(role, this.defKeys)
      this.rightDialogVisible = true
    },
    // *通过递归的形式，获取角色三级权限id,保存到defKeys
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // *监听分配权限对话框关闭
    rightDialogClose () {
      this.defKeys = []
    },
    // *树状控件分配权限
    allotRights () {
      const ids = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(ids)
      const idStr = ids.join(',')
      // console.log(idStr)
      this.$http.allotRights(this.treeId, idStr)
        .then(resp => {
          // console.log(resp)
          const { data: res } = resp
          if (res.meta.status !== 200) {
            return this.$message.error('更新权限失败')
          }
          this.$message.success(res.meta.msg)
          this.getRolesList()
          this.rightDialogVisible = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
  .roles {
    &-card {
      margin-top: 15px;
      &-button {
        margin-bottom: 15px;
      }
      .el-table-column {
        margin: 15px 0;
      }
      .bdtop {
        border-top: 1px solid rgb(224, 221, 221);
      }
      .bdbottom {
        border-bottom: 1px solid rgb(224, 221, 221);
      }
      .el-tag {margin: 7px;}
      .vcenter {
        display: flex;
        align-items: center;
      }
    }
    .cell {font-size: 13px;}
  }
</style>
